<template>
  <div>
    <el-form
      :model="addForm"
      ref="addFormRef"
      :rules="rules"
      label-position="top"
    >
      <el-form-item label="姓名" prop="name">
        <el-input v-model="addForm.name" placeholder="请输入姓名" />
      </el-form-item>
      <el-form-item label="性别" prop="sex">
        <el-radio-group v-model="addForm.sex">
          <el-radio-button label="男" :value="1" />
          <el-radio-button label="女" :value="2" />
        </el-radio-group>
      </el-form-item>
      <el-form-item label="联系方式" prop="phoneNumber">
        <el-input v-model="addForm.phoneNumber" placeholder="请输入联系方式" />
      </el-form-item>
      <el-form-item label="身份证号" prop="idCard">
        <el-input v-model="addForm.idCard" placeholder="请输入身份证号" />
      </el-form-item>
      <el-form-item label="所在部门及职位">
        <div
          v-for="(item, index) in tableData"
          :key="index"
          class="w-full flex justify-between items-center mb-1"
        >
          <el-select
            v-model="item.departmentId"
            filterable
            placeholder="请选择部门"
            class="w-[40%]"
            @change="
              item.positionId = null;
              getPositionList(item.departmentId, index);
            "
          >
            <el-option
              v-for="(item, index) in props.departmentList"
              :key="index"
              :label="item.departmentName"
              :value="item.id"
            />
          </el-select>
          <el-select
            v-model="item.positionId"
            filterable
            :placeholder="item.departmentId ? '请选择职位' : '请先选择部门'"
            class="w-[40%]"
          >
            <el-option
              v-for="(item, index) in item.positionList"
              :key="index"
              :label="item.positionName"
              :value="item.id"
            />
          </el-select>
          <el-button
            icon="Delete"
            type="danger"
            link
            title="删除"
            @click="handleDeleteDepartment(index)"
          ></el-button>
        </div>
        <div class="w-full">
          <el-button
            icon="Plus"
            class="w-full"
            type="info"
            @click="handleAddDepartment"
          ></el-button>
        </div>
      </el-form-item>
    </el-form>

    <div class="fixed bottom-2 right-2">
      <el-button>取消</el-button>
      <el-button type="primary" :loading="loading" @click="handleSubmit">
        {{ loading ? "提交中..." : "提交" }}
      </el-button>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { cloneDeep } from "lodash";
import { handleApiResponse } from "@/utils/request.js";
import {
  GetPositionListForDepartment,
  GetOrganizeEmployeeById,
  CreateOrganizeEmployee,
  UpdateOrganizeEmployee,
} from "../../../../../../wailsjs/go/api/CustomerApi";

onMounted(() => {
  if (props.detailForm.id != 0) {
    getDetail();
  }
});

const emit = defineEmits(["handleBack"]);
const props = defineProps({
  detailForm: {
    type: Object,
    default: () => ({}),
  },
  departmentList: {
    type: Array,
    default: () => [],
  },
});

const addFormRef = ref(null);
const addForm = ref({
  name: "",
  idCard: "",
  phoneNumber: "",
  sex: 1,
  departmentPositionList: [],
});

const loading = ref(false);
const handleSubmit = () => {
  addFormRef.value.validate((valid) => {
    if (!valid) return;
    loading.value = true;
    let form = cloneDeep(addForm.value);

    tableData.value.forEach((item) => {
      if (item.departmentId) {
        props.departmentList.forEach((dep) => {
          if (dep.id == item.departmentId) {
            item.departmentName = dep.departmentName;
          }
        });
      }
      if (item.positionId) {
        item.positionList.forEach((pos) => {
          if (pos.id == item.positionId) {
            item.positionName = pos.positionName;
          }
        });
      }
      delete item.positionList;
    });

    form.departmentPositionList = tableData.value;
    // console.log(form);
    if (props.detailForm.id == 0) {
      handleApiResponse(() => CreateOrganizeEmployee(form)).then((res) => {
        if (res.code == 0) {
          ElMessage.success("添加成功");
          emit("handleBack", 1);
        }
        loading.value = false;
      });
    } else {
      handleApiResponse(() => UpdateOrganizeEmployee(form)).then((res) => {
        if (res.code == 0) {
          ElMessage.success("编辑成功");
          emit("handleBack", 1);
        }
        loading.value = false;
      });
    }
  });
};

// 部门及职位列表
const tableData = ref([
  {
    departmentId: null,
    departmentName: "",
    positionId: null,
    positionName: "",
    positionList: [],
  },
]); // 部门职位列表

// 添加单个部门职位
const handleAddDepartment = () => {
  tableData.value.push({
    departmentId: null,
    departmentName: "",
    positionId: null,
    positionName: "",
    positionList: [],
  });
};
// 删除单个部门职位
const handleDeleteDepartment = (index) => {
  tableData.value.splice(index, 1);
};

// 职位列表
async function getPositionList(departmentId, index) {
  handleApiResponse(() => GetPositionListForDepartment({ departmentId })).then(
    (res) => {
      if (res.code == 0) {
        tableData.value[index].positionList = res.data.list || [];
      }
    }
  );
}

// 获取详情
async function getDetail() {
  handleApiResponse(() =>
    GetOrganizeEmployeeById({ id: props.detailForm.id })
  ).then((res) => {
    if (res.code == 0) {
      //   console.log(res.data);
      addForm.value = res.data || {};
      tableData.value = res.data.employeeDepartmentPositionInfo || [];
      tableData.value.forEach((item, index) => {
        getPositionList(item.departmentId, index);
      });
    }
  });
}

const rules = ref({
  name: [{ required: true, message: "请输入姓名" }],
  idCard: [
    { required: true, message: "请输入身份证号" },
    {
      min: 18,
      max: 18,
      message: "长度为18位",
    },
  ],
  phoneNumber: [
    { required: true, message: "请输入联系方式" },
    {
      pattern: /^1[3-9]\d{9}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
    { min: 11, max: 11, message: "长度为11位" },
  ],
  sex: [
    {
      required: true,
      message: "请选择性别",
    },
  ],
});
</script>

<style scoped lang="scss">
</style>